package com.hcy.app.screen.element

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ScrollableTabRow
import androidx.compose.material3.Tab
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.launch

@Preview
@Composable
private fun Material3TabsWithPagerPreview() {
    Material3TabsWithPager()
}
// 类似 el Tabs 标签页的效果
@Composable
fun Material3TabsWithPager() {
    val tabs = listOf("Tab 1", "Tab 2", "Tab 3","Tab 4", "Tab 5", "Tab 6")
    val pagerState = rememberPagerState { tabs.size } // 总页数
    val coroutineScope = rememberCoroutineScope() // 用于启动协程
    Column {
        ScrollableTabRow(
            selectedTabIndex = pagerState.currentPage,
            containerColor = Color.Transparent,
            contentColor = MaterialTheme.colorScheme.onSurface,
            edgePadding = 8.dp,
        ) {
            // compose很大的一个优势，就是可以代码化，高阶语法的形式来实现UI的逻辑
            tabs.forEachIndexed { index, model ->
                Tab(
                    text = { Text(model) },
                    selected = pagerState.currentPage == index,
                    onClick = {
                        coroutineScope.launch {
                            pagerState.animateScrollToPage(index)
                        }
                    },
                )
            }
        }
        // 2. 横向滑动页面
        HorizontalPager(
            state = pagerState,
            modifier = Modifier.weight(1f)
        ) { pageIndex ->
            when(pageIndex){
                0->Box(
                    modifier = Modifier.fillMaxSize().background(Color.Blue),
                    contentAlignment = Alignment.Center
                ) {
                    Text("我是第一个页面")
                }
                1->Box(
                    modifier = Modifier.fillMaxSize().background(Color.Yellow),
                    contentAlignment = Alignment.Center
                ) {
                    Text("我是第二个页面")
                }
                else -> Box(
                    modifier = Modifier.fillMaxSize().background(Color.Red),
                    contentAlignment = Alignment.Center
                ) {
                    Text("我是第default页面")
                }
            }
        }
        // 3. 同步 Tab 点击与 Pager 滑动
        LaunchedEffect(pagerState.currentPage) {
            // 自动滚动到对应页面（可选）
            pagerState.animateScrollToPage(pagerState.currentPage)
        }
    }

}
